<template>
  <el-row>
    <el-col :span="14">
      <el-form ref="form" :model="form" :rules="rules" label-position="right" label-width="150px">
        <el-form-item prop="name">
          <span slot="label">头像设置: </span>
          <el-row>
            <el-col :span="12">
              <el-upload
                class="avatar-uploader"
                action="#"
                :http-request="myUpload"
                :show-file-list="false"
              >
                <img :src="$store.getters.avatar" class="avatar">
              </el-upload>
            </el-col>
            <el-col :span="8" class="changImage">
              <i class="el-icon-back" />
              <span>点击头像更换</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item prop="userAccount">
          <span slot="label">账号:</span>
          <el-input v-model="form.userAccount" disabled />
        </el-form-item>
        <el-form-item ref="userPassword" prop="userPassword">
          <span slot="label">原密码:</span>
          <el-input v-model="form.userPassword" show-password placeholder="留空则不变" />
        </el-form-item>
        <el-form-item prop="userEmail">
          <span slot="label">邮箱:</span>
          <el-input v-model="form.userEmail" disabled />
        </el-form-item>
        <el-form-item prop="userName">
          <span slot="label">真实姓名:</span>
          <el-input v-model="form.userName" />
        </el-form-item>
        <el-form-item prop="userSchool" label="学校">
          <el-input v-model="form.userSchool" placeholder="学校，比如河南大学" />
        </el-form-item>
        <el-form-item label="入学年份" prop="userGrade" style="text-align: left">
          <el-date-picker
            v-model="form.userGrade"
            type="year"
            value-format="yyyy"
            placeholder="年级，如2022级"
          />
        </el-form-item>
        <el-form-item prop="userName">
          <span slot="label">真实姓名:</span>
          <el-input v-model="form.userName" />
        </el-form-item>
        <el-form-item prop="userRole">
          <span slot="label">队员状态:</span>
          <el-radio v-model="form.userRole" :label="parseInt('1')">现役队员</el-radio>
          <el-radio v-model="form.userRole" :label="parseInt('0')">退役队员</el-radio>
        </el-form-item>
        <el-form-item ref="newPass" prop="newPass">
          <span slot="label">新密码:</span>
          <el-input v-model="form.newPass" show-password placeholder="如您修改密码，您的登录账号会被强制登出。" />
        </el-form-item>
        <el-form-item ref="checkPass" prop="checkPass">
          <span slot="label">再次输入:</span>
          <el-input v-model="form.checkPass" show-password />
        </el-form-item>
        <el-form-item prop="userMotto">
          <span slot="label">个人简介:</span>
          <el-input v-model="form.userMotto" type="textarea" placeholder="一句话或者一个目标~" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">立即修改</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script>
import { updateInfo, uploadImage } from '@/networks/info'
import { dataURLtoFile } from '@/utils/utils'
import router from '@/router'
const lrz = require('lrz')
export default {
  name: 'Security',

  data() {
    const validatePass = (rule, value, callback) => {
      if (this.form.checkPass !== '') {
        this.$refs.form.validateField('checkPass')
      }
      callback()
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '' && this.form.newPass !== '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== null && value !== this.form.newPass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      form: {
        userAccount: '',
        userEmail: '',
        userName: '',
        userPassword: '',
        newPass: '',
        checkPass: '',
        userMotto: '',
        userRole: 0,
        userGrade: '',
        userSchool: ''
      },
      rules: {
        userName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        userPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPass: [
          { validator: validatePass, trigger: 'blur' },
          { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' },
          { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
        ]
      },
      imgType: ['bmp', 'png', 'tif', 'gif', 'jpeg']
    }
  },
  mounted() {
    this.init()
  },
  activated() {
    this.init()
  },
  methods: {
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          updateInfo(this.form).then(res => {
            const data = res.data
            if (data.status === 0) {
              this.$message.error(data.msg)
            } else if (data.status === 1) {
              this.$message.success(data.msg)
              this.$store.commit('setUser', data.data)
            } else {
              this.$message.success(data.msg)
              this.$store.commit('del')
              this.$router.push({
                path: '/login',
                query: { redirect: router.currentRoute.fullPath }// 登录成功后跳入浏览的当前页面
              })
            }
          })
        } else {
          return false
        }
      })
    },

    resetForm() {
      this.$refs.userPassword.resetField()
      this.$refs.newPass.resetField()
      this.$refs.checkPass.resetField()
    },
    myUpload(content) {
      const file = content.file
      console.log(file)
      this.before = file.size / 1024
      this.imgUrl = URL.createObjectURL(file, { quality: 0 })

      const type = file.type.toLowerCase()
      if (this.imgType.findIndex(res => type === ('image/' + res)) === -1) {
        this.$message.error('只能上传bmp,png,tif,gif,jpeg')
        return
      }

      // eslint-disable-next-line no-undef
      lrz(this.imgUrl).then(rst => {
        // 压缩后文件大小
        console.log(rst)
        const tempFile = dataURLtoFile(rst.base64, file.name)
        tempFile.uid = rst.origin.uid
        const form = new FormData()
        form.append('file', tempFile)
        uploadImage(form).then(res => {
          const data = res.data
          if (data.status === 1) {
            this.$store.commit('updateAvatar', data.data)
            this.$message.success(data.msg)
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    init() {
      const user = this.$store.state.user
      this.form.userName = user.userName
      this.form.userAccount = user.userAccount
      this.form.userEmail = user.userEmail
      this.form.userRole = user.userRole
      this.form.userMotto = user.userMotto
      this.form.newPass = ''
      this.form.userPassword = ''
      this.form.checkPass = ''
      this.form.userGrade = user.userGrade
      this.form.userSchool = user.userSchool
    }
  }
}
</script>

<style scoped>
  .el-form {
    padding-top: 50px;
  }

  .el-form-item {
    padding-top: 10px;
  }

  .avatar-uploader >>> .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 200px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader >>> .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .changImage {
    position: relative;
    top: 80px;
    font-size: 18px;
    color: #b4b4b4;
  }
</style>
